#!/usr/bin/env python3
"""
脚本执行器
用于在命令行直接执行脚本时自动添加项目根目录到Python路径
使用方法: python run_script.py <脚本路径>
"""

import os
import sys
import importlib.util
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('ScriptRunner')

def run_script(script_path):
    """
    执行指定路径的脚本
    :param script_path: 脚本文件路径
    """
    if not os.path.exists(script_path):
        logger.error(f"脚本文件不存在: {script_path}")
        return 1
    
    # 获取项目根目录
    project_root = os.path.dirname(os.path.abspath(__file__))
    
    # 添加项目根目录到Python路径
    if project_root not in sys.path:
        sys.path.insert(0, project_root)
        logger.info(f"已添加项目根目录到Python路径: {project_root}")
    
    try:
        # 动态加载模块
        module_name = os.path.basename(script_path).replace('.py', '')
        spec = importlib.util.spec_from_file_location(module_name, script_path)
        if spec is None or spec.loader is None:
            logger.error(f"无法加载脚本: {script_path}")
            return 1
        
        module = importlib.util.module_from_spec(spec)
        sys.modules[module_name] = module
        spec.loader.exec_module(module)
        
        logger.info(f"脚本 {script_path} 执行完成")
        return 0
    except Exception as e:
        logger.error(f"执行脚本时出错: {str(e)}")
        import traceback
        traceback.print_exc()
        return 1

def main():
    if len(sys.argv) < 2:
        print(f"使用方法: {sys.argv[0]} <脚本路径>")
        return 1
    
    script_path = sys.argv[1]
    # 将剩余参数传递给脚本
    sys.argv = [script_path] + sys.argv[2:]
    
    return run_script(script_path)

if __name__ == "__main__":
    sys.exit(main())